package com.apes.scm.masterdata.car.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.car.model.CarModel;
import com.apes.scm.masterdata.car.model.CarModelServiceLevel;
import com.apes.scm.masterdata.car.model.CarServiceLevel;
import com.apes.scm.masterdata.car.repository.CarModelServiceLevelRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 配置 车型服务等级Service
 * @author weisj
 * @create 2018-07-31
 * @since 1.0.0
 */
@Service("carModelServiceLevelService")
public class CarModelServiceLevelService extends DomainService {
    @Autowired
    CarModelServiceLevelRepository carModelServiceLevelRepository;

    public CarModelServiceLevel save (SimpleRequest request){
        CarModelServiceLevel carModelServiceLevel = request.getO(CarModelServiceLevel.class);
        return carModelServiceLevelRepository.saveAndFlush(carModelServiceLevel);
    }

    public Page<CarModelServiceLevel> findAll (SimpleRequest request) {
        List<Map> filters = request.get("condition");
        return carModelServiceLevelRepository.findAll(JpaDsl.toCriteria(filters),PageRequest.of(request.get("page"), request.get("size")));
    }

    public Page<CarServiceLevel> findCarServiceLevel (SimpleRequest request) {
        String key = request.get("key");
        return carModelServiceLevelRepository.find(key,key,PageRequest.of(request.get("page"), request.get("size")));
    }

    public String delete(SimpleRequest request) throws Exception  {
        String id = request.get("id");
        Integer versions = request.get("version");
        CarModelServiceLevel carModelServiceLevel = carModelServiceLevelRepository.findOne(id);
        if (carModelServiceLevel == null) throw new RuntimeException("车型服务等级【" + id + "】在系统中不存在。");
        if (carModelServiceLevel.getVersion() != versions) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        carModelServiceLevelRepository.delete(carModelServiceLevel);
        return "删除成功";
    }

    public Page<CarModel> findCarModel (SimpleRequest request) {
        String key = request.get("key");
        return carModelServiceLevelRepository.findCarModel(key,key,PageRequest.of(request.get("page"), request.get("size")));
    }
}
